<template>
  <button class="va-df-action-button" :type="type" :style="[action.buttonStyle]" :class="[commonClasses.commonButtonClass, action.buttonClass]" @click.prevent="clickHandler">
    <span v-html="labelHtml"></span>
    <div class="va-df-button-loading" v-if="action.pending">
      <i class="va-icon-spinner-fish ann-rotation"></i>
    </div>
  </button>
</template>

<script>
  import _ from 'lodash'
  import LocaleMixin from '../locales/mixin'
  import Emitter from '../utils/emitter-mixin'

  export default {
    name: 'DynamicFormActionButton',
    mixins: [LocaleMixin, Emitter],
    props: {
      /*
      * 按钮配置对象{
      *   buttonStyle,
      *   buttonClass,
      *   type, // submit/reset/button，默认为 button
      *   label // 标签，字符串或Html串，如果为空，则为type名称
      * }
      * */
      action: {
        type: Object,
        required: true
      }
    },
    computed: {
      form () {
        return this.getDynamicForm()
      },
      commonClasses () {
        return (this.form && this.form.formSchema && this.form.formSchema.commonClasses) || {}
      },
      type () {
        if (!this.action.type) {
          return 'button'
        }
        switch (this.action.type) {
          case 'submit':
          case 'reset':
          case 'button':
            return this.action.type
        }
        throw new Error('action button type error...')
      },
      labelHtml () {
        if (_.isFunction(this.action.label)) {
          return this.action.label(this.model, this.formModel, this.field, this.action)
        }
        return this.action.label || this.lang('buttons.' + this.action.type)
      }
    },
    methods: {
      clickHandler () {
        this.$emit('action', this.action)
        return false
      }
    }
  }
</script>
